from json import JSONDecodeError
import paho.mqtt.client as mqtt
import os
import sys
sys.path.extend(['../'])
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Diot_web.settings")
django.setup()
from main.models import DeviceData
from django.utils import timezone
import json
import logging
from sms.sm_sender import send_warning

sms_last_send_time = timezone.now()


# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("Diot_devecor")


# The callback for when a PUBLISH message is received from the server.
def on_message(client: mqtt.Client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    d = None
    try:
        d = json.loads(msg.payload)
    except JSONDecodeError as err:
        logging.error(err)
    else:
        # 发送警示短信
        now = timezone.now()
        c_value = float(d["percentage"])
        delta = now - sms_last_send_time
        if delta.total_seconds() > 600 and c_value > 4:
            send_warning(1, c_value, ["+86xxxxxxxxxxx"])

        # 存储数据
        dd = DeviceData(**d)
        dd.save()


def main():

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    try:
        client.connect("mqtt.eclipse.org", 1883, 60)
    except OSError as err:
        logging.error(err)
    else:
        client.loop_forever()


if __name__ == "__main__":
    main()
